<?php
/*
 * @Author: zwx
 * @Date: 2024-05-08 10:39:41
 * @LastEditors: zwx
 * @LastEditTime: 2024-05-30 17:15:56
 * @Description: 私域直播数字人
 */

namespace app\apiadmin\controller\live;

use app\apiadmin\service\TCSS\TImService;
use app\common\controller\BaseController;
use app\common\utils\Res;
use app\Request;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Db;

class Shuziren extends BaseController
{

    /**
     * @author: zwx
     * @Description: 获取数字人类型数组
     * @Date: 2024-05-08 15:41:00
     */
    public function typedata()
    {

        $data = DB::table('xh_siyu_shuziren_flag')->where(array('del' => 0))->select();

        return Res::ok($data);
    }

    /**
     * @author: zwx
     * @Description: 获取数字人列表
     * @Date: 2024-05-08 15:41:00
     */
    public function getdata()
    {
        $param = $this->request->param();

        $size = $param['size'] ? $param['size'] : 10; //每页显示条数
        $page = $param['page'] ? $param['page'] : 1; //当前页数

        $type = $param['type'] ? $param['type'] : 1; //昵称或内容
        $input = $param['input'] ? $param['input'] : false; //输入的内容
        $flag = $param['flag'] ? $param['flag'] : -1; //数字人类型

        $where = array();
        $where[] = ['xh_siyu_shuziren_list.del', '=', 0];

        if ($type == 1) {
            if ($input != '' && $input) {
                $where[] = array('nick', 'like', '%' . $input . '%');
            }
        } else if ($type == 2) {
            if ($input != '' && $input) {
                $where[] = array('pinglun', 'like', '%' . $input . '%');
            }
        }

        if ($flag > -1) {
            $where[] = ['flagid', '=', $flag];
        }

        $data = array();
        $result = DB::table('xh_siyu_shuziren_list')
            ->join('xh_siyu_shuziren_flag', 'xh_siyu_shuziren_list.flagid=xh_siyu_shuziren_flag.id', "left")
            ->where($where)
            ->order('id desc')
            ->page($page, $size)
            ->field("xh_siyu_shuziren_list.*,xh_siyu_shuziren_flag.name as flagname")
            ->select();
        $count = DB::table('xh_siyu_shuziren_list')
            ->where($where)
            ->count();

        $data = [
            'list' => $result,
            'total' => $count,
        ];

        return Res::ok($data);
    }

    /**
     * @author: zwx
     * @Description: 创建数字人
     * @Date: 2024-05-09 11:21:47
     */
    public function createShuziren()
    {

        $param = $this->request->param();
        $nick = $param['nick']; //每页显示条数
        $pinglun = $param['pinglun']; //每页显示条数
        $flagid = $param['flagid']; //每页显示条数
        $touxiang_img = $param['touxiang_img']; //每页显示条数

        if (!$flagid || $flagid == '') {
            return Res::error('类型不能为空');
        }
        if (!$pinglun || $pinglun == '') {
            return Res::error('评论不能为空');
        }

        $data = array();
        $data['nick'] = $nick;
        $data['pinglun'] = $pinglun;
        $data['flagid'] = $flagid;
        $data['touxiang_img'] = $touxiang_img;
        $data['createtime'] = date('Y-m-d H:i:s');

        $imService = new TImService();
        $insertId = null;
        Db::startTrans();
        try {

            $insertId = DB::table('xh_siyu_shuziren_list')->insert($data, true);
            $insertId = "R_" . env("Live.live_pre") . $insertId;
            // 添加账号
            $ret = $imService->account_import_one($insertId, $data["nick"], $data["touxiang_img"]);
            if ($ret !== true) {
                throw new \Exception("导入账号失败");
            }
            Db::commit();
            return Res::ok($insertId);

        } catch (\Throwable $th) {

            if (empty($insertId)) {
                $imService->account_delete_ids([$insertId]);
            }
            Db::rollback();
            // throw $th;

            return Res::error($th->getMessage());

        }

    }

    /**
     * @author: zwx
     * @Description: 删除数字人
     * @Date: 2024-05-09 14:16:52
     */
    public function delShuziren()
    {

        $param = $this->request->param();
        $id = $param['id'];
        $imService = new TImService();

        $data = DB::table('xh_siyu_shuziren_list')->where(array('id' => $id))->find();
        if ($data) {
            $a = DB::table('xh_siyu_shuziren_list')->where(array('id' => $id))->update(array('del' => 1));
            return Res::ok($a);
        } else {
            return Res::error('未查询到数据，请刷新重试');
        }

    }

    /**
     * @author: zwx
     * @Description: 修改数字人
     * @Date: 2024-05-09 11:21:47
     */
    public function editShuziren()
    {

        $param = $this->request->param();
        $id = $param['id'];
        $nick = $param['nick']; //每页显示条数
        $pinglun = $param['pinglun']; //每页显示条数
        $flagid = $param['flagid']; //每页显示条数
        $touxiang_img = $param['touxiang_img']; //每页显示条数

        $data = array();
        $data['nick'] = $nick;
        $data['pinglun'] = $pinglun;
        $data['flagid'] = $flagid;
        $data['touxiang_img'] = $touxiang_img;

        $dd = DB::table('xh_siyu_shuziren_list')->where(array('id' => $id))->find();

        if ($dd) {
            $a = DB::table('xh_siyu_shuziren_list')->where(array('id' => $id))->save($data);
            return Res::ok($a);
        } else {
            return Res::error('未查询到数据，请刷新重试');
        }

    }

    /**
     * @author: zwx
     * @Description: 批量删除数字人
     * @Date: 2024-05-09 14:16:52
     */
    public function pldelShuziren()
    {

        $param = $this->request->param();
        $ids = $param['ids'];

        $where = array();
        $where[] = ['id', 'in', $ids];

        $data = DB::table('xh_siyu_shuziren_list')->where($where)->select();
        if ($data) {
            $a = DB::table('xh_siyu_shuziren_list')->where($where)->update(data: array('del' => 1));
            return Res::ok($a);
        } else {
            return Res::error('未查询到数据，请刷新重试');
        }

    }

    /**
     * @author: zwx
     * @Description: 批量导入数字人
     * @Date: 2024-05-09 14:16:52
     */
    public function daorushuziren()
    {

        // 接收上传的文件
        $file = $this->request->file('file');

        // 验证文件是否上传成功
        if (!$file) {
            return json(['error' => 'No file uploaded'], 400);
        }

        // 移动文件到临时目录
        $tmpPath = $file->move('runtime/temp/')->getPathname();

        // 读取Excel文件
        $spreadsheet = IOFactory::load($tmpPath);
        $worksheet = $spreadsheet->getActiveSheet();

        // 遍历工作表获取数据
        $data = [];
        foreach ($worksheet->getRowIterator(2) as $row) {
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false);

            $rowData = [];
            foreach ($cellIterator as $k => $cell) {
                if ($cell->getValue() != null) {
                    $rowData[] = $cell->getValue();
                } else {
                    return Res::error('数据不能为空');
                    break;
                    die;
                }

            }
            if (count($rowData) == 0) {
                continue;
            }
            $data[] = $rowData;

        }

        // 删除上传的文件
        unlink($tmpPath);

        $param = $this->request->param();
        $flagid = $param['flagid'];
        $batchImportAccount = [];
        $dd = array();
        foreach ($data as $k => $v) {
            $a = array();
            foreach ($v as $k1 => $v1) {
                if ($k1 == 0) {
                    $a['touxiang_img'] = $v1;
                } else if ($k1 == 1) {
                    $a['nick'] = $v1;
                } else if ($k1 == 2) {
                    $a['pinglun'] = $v1;
                }
            }
            $a['flagid'] = $flagid;
            $a['createtime'] = date('Y-m-d H:i:s');
            $dd[] = $a;
            $batchImportAccount[] = [

            ];

        }
        // return Res::ok($dd);

        try {
            // dump($dd);die;
            $d = DB::table('xh_siyu_shuziren_list')->insertAll($dd);
            return Res::ok($d);
        } catch (\Exception $e) {
            // 处理异常
            echo $e->getMessage();
        }

    }

    public function import(Request $request)
    {
        // 接收上传的文件
        $file = $request->file('excel');

        // 验证文件是否上传成功
        if (!$file) {
            return json(['error' => 'No file uploaded'], 400);
        }

        // 移动文件到临时目录
        $tmpPath = $file->move('runtime/temp/')->getPathname();

        // 读取Excel文件
        $spreadsheet = IOFactory::load($tmpPath);
        $worksheet = $spreadsheet->getActiveSheet();

        // 遍历工作表获取数据
        $data = [];
        foreach ($worksheet->getRowIterator() as $row) {
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false);
            $rowData = [];
            foreach ($cellIterator as $cell) {
                $rowData[] = $cell->getValue();
            }
            $data[] = $rowData;
        }

        // 处理$data，例如保存到数据库
        // ...

        // 删除临时文件
        @unlink($tmpPath);

        return json(['message' => 'Excel imported successfully', 'data' => $data]);
    }

    /*****************************          数字人类型                     ******************************* */

    /**
     * @author: zwx
     * @Description: 获取数字人类型列表
     * @Date: 2024-05-08 15:41:00
     */
    public function getdatagroup()
    {
        $param = $this->request->param();

        $size = $param['size'] ? $param['size'] : 10; //每页显示条数
        $page = $param['page'] ? $param['page'] : 1; //当前页数

        $input = $param['input'] ? $param['input'] : false; //输入的内容

        $where = array();
        $where[] = ['del', '=', 0];
        if ($input) {
            $where[] = array('name', 'like', '%' . $input . '%');
        }

        $data = array();
        $result = DB::table('xh_siyu_shuziren_flag')
            ->where($where)
            ->order('id desc')
            ->page($page, $size)
            ->select();
        $count = DB::table('xh_siyu_shuziren_flag')->where($where)->count();
        $data = [
            'list' => $result,
            'total' => $count,
        ];

        return Res::ok($data);
    }

    /**
     * @author: zwx
     * @Description: 创建数字人类型
     * @Date: 2024-05-09 11:21:47
     */
    public function createShuzirengroup()
    {

        $param = $this->request->param();
        $name = $param['name']; //名称
        $remark = $param['remark']; //备注

        if (!$name || $name == '') {
            return Res::error('类型不能为空');
        }

        $data = array();
        $data['name'] = $name;
        $data['remark'] = $remark;
        $data['createtime'] = date('Y-m-d H:i:s');
        $id = DB::table('xh_siyu_shuziren_flag')->insert($data);

        return Res::ok($id);

    }

    /**
     * @author: zwx
     * @Description: 删除数字人类型
     * @Date: 2024-05-09 14:16:52
     */
    public function delShuzirengroup()
    {

        $param = $this->request->param();
        $id = $param['id'];

        $data = DB::table('xh_siyu_shuziren_flag')->where(array('id' => $id))->find();
        //查询一下 数值人列表中是否有数据
        $count = DB::table("xh_siyu_shuziren_list")->where(array("flagid" => $id, "del" => 0))->count();
        if ($data) {
            // 判断是否有数据 如果有数那么不允许删除
            if ($count > 0) {
                return Res::error("该类型下有数据，不可删除");
            }
            $a = DB::table('xh_siyu_shuziren_flag')->where(array('id' => $id))->update(array('del' => 1));
            return Res::ok($a);
        } else {
            return Res::error('未查询到数据，请刷新重试');
        }

    }

    /**
     * @author: zwx
     * @Description: 修改数字人类型
     * @Date: 2024-05-09 11:21:47
     */
    public function editShuzirengroup()
    {

        $param = $this->request->param();
        $id = $param['id'];
        $name = $param['name']; //名称
        $remark = $param['remark']; //备注

        $data = array();
        $data['name'] = $name;
        $data['remark'] = $remark;

        $dd = DB::table('xh_siyu_shuziren_flag')->where(array('id' => $id))->find();

        if ($dd) {
            $a = DB::table('xh_siyu_shuziren_flag')->where(array('id' => $id))->save($data);
            return Res::ok($a);
        } else {
            return Res::error('未查询到数据，请刷新重试');
        }

        return Res::ok($id);

    }

    /**
     * @author: zwx
     * @Description: 批量删除数字人类型
     * @Date: 2024-05-09 14:16:52
     */
    public function pldelShuzirengroup()
    {

        $param = $this->request->param();
        $ids = $param['ids'];

        $where = array();
        $where[] = ['id', 'in', $ids];

        $data = DB::table('xh_siyu_shuziren_flag')->where($where)->select();
        if ($data) {
            $a = DB::table('xh_siyu_shuziren_flag')->where($where)->update(array('del' => 1));
            return Res::ok($a);
        } else {
            return Res::error('未查询到数据，请刷新重试');
        }

    }

    public function syncToIM()
    {

    }

}
